'use strict'
const { Register } = require('../model/login');
const jwt = require('jsonwebtoken');
const { try_parse_json } = require('../../azeroth');
class Login {

    constructor() {
        this.secret = 'xinshijituan';
        this.token = null;
        this.init();
    }
    // 初始化，解决async
    async init() {
        this.id = await Register.getmaxId();
    }
    // 处理新用户
    async handNewUser(userInfo) {
        try {
            // 创建token 并存储密钥
            await jwt.sign({ username: userInfo.username, password: userInfo.password }, this.secret, async (err, token) => {
                if (err) {
                    console.log(err);
                    return err;
                }
                this.token = token;
            });
            let res = await Register.createUser({
                ...userInfo,
                id: ++this.id
            });
            console.log(res);
            if (res.dataValues) {
                return {
                    token: this.token
                };
            }
        } catch (_) {
            console.log(_);
        }
    }

    static getInstance() {
        if (Login.instance) {
            return Login.instance;
        } else {
            Login.instance = new Login();
            return Login.instance;
        }
    }
}

module.exports = Login.getInstance();